﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using XCI.Sys.Helper;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows.Helper;

namespace XCI.Sys.Forms
{
    public partial class FrmModuleAuthorize : FrmSysBase
    {
        private TreeHelper<SysModule> helper;
        private ModuleHelper moduleHelper;
        private readonly string objectId;
        private readonly string title;

        public FrmModuleAuthorize(string _objectId, string _title)
        {
            InitializeComponent();
            objectId = _objectId;
            title = _title;
        }

        /// <summary>
        /// 页面初始化
        /// </summary>
        private void InitForm()
        {
            captionControl1.CaptionText = title;

            moduleHelper = new ModuleHelper(treeListx1);
            helper = new TreeHelper<SysModule>(treeListx1);
            helper.AutoCheckedParentNode = true;
            helper.AutoCheckedChildNode = true;
            helper.IsApplyCheckedRowStyle = true;
            LoadData();
        }

        /// <summary>
        /// 数据加载
        /// </summary>
        private void LoadData()
        {
            var data = ModuleService.Instance.SelectListByUserId(CurrentUser.Id);
            helper.SetDataSource(data);

            var ids = ModuleService.Instance.SelectModuleMapArrayByObjectId(objectId);
            helper.SetCheckedNodeIds(ids);
            timer1.Start();
        }

        private void FrmModuleAuthorize_Load(object sender, EventArgs e)
        {
            InitForm();
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
            moduleHelper.InitModuleImageList(treeImageList, false);
            moduleHelper.ExpandNode();
        }

        private void TreeListx1_GetStateImage(object sender, DevExpress.XtraTreeList.GetStateImageEventArgs e)
        {
            e.NodeImageIndex = moduleHelper.GetModuleImageIndex(e.Node);
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            ModuleService.Instance.SaveModuleMap(objectId, helper.CheckedIds);
            ResultOk();
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            ResultCancel();
        }
    }
}